// ICE候选者类型示例
const candidateTypes = {
    host: "本地网络候选者",
    srflx: "服务器反射候选者(STUN)",
    relay: "中继候选者(TURN)"
};
class LANWebRTCConnection {
    // 链接对象管理
    connections = new Map();
    peerConnection = null; //单用户链接，也就是接收方
    peerId = null;//用户链接记录唯一链接id
    // 存储开播的流
    stream = null;
    constructor() {
        this.connections = new Map(); // key: peerId, value: RTCPeerConnection
        this.peerConnection = null;
        this.dataChannel = null;
        this.broadcastChannel = null;
        this.init();
    }
    // 获取广播通道
    getBroadcastChannel() {
        return this.broadcastChannel;
    }
    init() {
        console.log("初始化 LANWebRTCConnection");
        // 初始化广播通道作为简单的信令
        this.broadcastChannel = new BroadcastChannel('lan-webrtc');

        // 设置广播通道的消息处理
        this.broadcastChannel.onmessage = async (event) => {
            const { type, data } = event.data;
            console.log(`收到广播消息: ${type} 数据 ：${JSON.stringify(data)}}`);

            switch (type) {
                case 'join':
                    await this.handleJoin(data);
                    break;
                case 'offer':
                    await this.handleOffer(data);
                    break;
                case 'answer':
                    await this.handleAnswer(data);
                    break;
                case 'ice-candidate':
                    await this.handleIceCandidate(data);
                    break;
            }
        };
    }
    // 事件监听
    initEvent(peerConnection) {
        // 设置ICE候选者处理
        peerConnection.onicecandidate = ({ candidate }) => {
            if (candidate) {
                // 将RTCIceCandidate对象转换为普通对象
                const candidateObj = {
                    candidate: candidate.candidate,
                    sdpMid: candidate.sdpMid,
                    sdpMLineIndex: candidate.sdpMLineIndex,
                    usernameFragment: candidate.usernameFragment
                };

                const candidateType = candidate.candidate.split(' ')[7];
                console.log("候选者类型:", candidateTypes[candidateType]);
                this.broadcastChannel.postMessage({
                    type: 'ice-candidate',
                    data: candidateObj
                });
            }
        };
        // ICE连接状态
        peerConnection.oniceconnectionstatechange = () => {
            console.log("ICE状态:", peerConnection.iceConnectionState);
        };

        // 信令状态
        peerConnection.onsignalingstatechange = () => {
            console.log("信令状态:", peerConnection.signalingState);
        };

        // 连接状态
        peerConnection.onconnectionstatechange = () => {
            console.log("连接状态:", peerConnection.connectionState);
        };
    }
    /**
 * 
 * @param {*} join 加入者的信息
 */
    async handleJoin(join) {
        console.log("收到加入者的信息", join);
        this.createPeerConnection(join.peerId);
    }
    // 创建webrtc链接
    async createPeerConnection(onlyKey, isSendOff = 1) {
        const peerC = new RTCPeerConnection(this.config);
        if (onlyKey) {
            this.connections.set(onlyKey, peerC);
            this.peerConnection = peerC; //如果是发起方这个是最后一个链接的用户
        }
        this.stream && this.addStreamToNewStudent(peerC);
        this.initEvent(peerC);
        isSendOff == 1 && this.createOffer(peerC)
    }
    addStreamToNewStudent(peerC) {
        this.stream.getTracks().forEach(track => {
            peerC.addTrack(track, this.stream);
        });
    }
    // 创建并发送offer（发起方）
    async createOffer(peerC) {
        this.dataChannel = peerC.createDataChannel('messageChannel');
        this.setupDataChannelEvent(this.dataChannel);
        console.log("创建并发送offer（发起方）");

        const offer = await peerC.createOffer();
        await peerC.setLocalDescription(offer);
        console.log("发送offer");

        this.broadcastChannel.postMessage({
            type: 'offer',
            data: offer
        });
    }

    // 处理收到的offer（接收方）
    async handleOffer(offer) {
        await this.peerConnection.setRemoteDescription(new RTCSessionDescription(offer));
        const answer = await this.peerConnection.createAnswer();
        await this.peerConnection.setLocalDescription(answer);

        this.broadcastChannel.postMessage({
            type: 'answer',
            data: { answer, peerId: this.peerId }
        });
    }

    // 处理收到的answer
    async handleAnswer({ answer, peerId }) {
        if (!this.connections.get(peerId)) {
            console.error(`未找到与${peerId}的连接`);
            return
        }
        await this.connections.get(peerId).setRemoteDescription(new RTCSessionDescription(answer));
    }

    // 处理ICE候选者
    async handleIceCandidate(candidate) {
        await this.peerConnection.addIceCandidate(new RTCIceCandidate(candidate));
    }

    // 设置数据通道
    setupDataChannelEvent(dataChannel) {
        dataChannel.onopen = () => {
            console.log('数据通道已打开');
        };

        dataChannel.onmessage = (event) => {
            console.log('收到消息:', event.data);
        };

        dataChannel.onclose = () => {
            console.log('数据通道已关闭');
        };
    }

    // 发送消息
    sendMessage(message) {
        if (this.dataChannel && this.dataChannel.readyState === 'open') {
            this.dataChannel.send(message);
        }
    }
    // 开始录播 将链接的用户添加流
    async startAddChunk(stream) {
        console.log('startAddChunk', this.connections);
        this.stream = stream;
        try {
            if (this.connections.size === 0) {
                console.error('没有可用的对等连接');
                return;
            }
            this.connections.forEach(async (connection, peerId) => {
                console.log('peerId', peerId, connection);
                stream.getTracks().forEach(track => {
                    connection.addTrack(track, stream);
                })
                const offer = await connection.createOffer();
                connection.setLocalDescription(offer);

                this.broadcastChannel.postMessage({
                    type: 'offer',
                    data: offer
                });

            })
        } catch (error) {
            console.error('Error adding track:', error);
        }
    }
    // 清理资源
    cleanup() {
        if (this.broadcastChannel) {
            this.broadcastChannel.close();
        }
        if (this.peerConnection) {
            this.peerConnection.close();
        }
    }
}

export default LANWebRTCConnection;